<template>
    <div>
        <slot v-for="(button, index) in visibleButtons" :key="index">
            <component
                :is="button.component || 'el-button'"
                v-bind="{
                    type: 'primary',
                    link: true,
                    ...button.props,
                }"
                v-hasPermi="button.props['v-hasPermi']"
                >{{ button.text }}</component
            >
        </slot>
        <template v-if="showMore">
            <el-popover
                v-model:visible="visible"
                trigger="hover"
                popper-class="popper-nav"
                placement="left"
                :hide-after="0"
            >
                <template #reference>
                    <el-button link type="primary">更多</el-button>
                </template>
                <component
                    v-for="(button, index) in moreButtons"
                    :key="index"
                    :is="button.component || 'el-button'"
                    v-bind="{
                        class: 'block',
                        type: 'primary',
                        link: true,
                        ...button.props,
                    }"
                    v-hasPermi="button.props['v-hasPermi']"
                    >{{ button.text }}</component
                >
            </el-popover>
        </template>
    </div>
</template>

<script setup>
import { onMounted, reactive, toRefs } from "vue";
import { onBeforeRouteLeave } from "vue-router";

const props = defineProps({
    buttons: {
        type: Array,
        required: true,
    },
});

const state = reactive({
    visibleButtons: [],
    showMore: false,
    moreButtons: [],
    visible: false,
});
const { visibleButtons, showMore, moreButtons, visible } = toRefs(state);

onBeforeRouteLeave(() => {
    // 解决切换路由瞬移到左上角的问题
    state.visible = false;
});

onMounted(() => {
    updateVisibleButtons();
});

const updateVisibleButtons = () => {
    // 超出3个按钮时，显示更多按钮
    const maxVisible = 3;
    // 过滤不渲染的按钮
    const btns = props.buttons.filter(
        (item) => !item.hasOwnProperty("isRender") || item.isRender
    );
    const length = btns.length;
    if (length > maxVisible) {
        state.visibleButtons = btns.slice(0, maxVisible - 1);
        state.moreButtons = btns.slice(maxVisible - 1);
        state.showMore = true;
    } else {
        state.visibleButtons = btns;
        state.showMore = false;
    }
};
</script>
